<?php

	class SocialAuth {

		private $_currentUser = false;
		private $_authenticated = false;

		private $_eiLoginUserId = 0;

		private $_facebookOauthService = false;
		private $_facebookUserProfile = false;
		private $_facebookUserFriends = false;

		private $_linkedinOauthService = false;
		private $_linkedinUserProfile = false;
		private $_linkedinUserFriends = false;

		private $_twitterOauthService = false;
		private $_twitterUserProfile = false;
		private $_twitterFriends = false;

		private $_message = false;

		function __construct( $service = 'facebook' ) {
			global $eiLoginUserId;
			$this->_eiLoginUserId = $eiLoginUserId;
			$this->_service = $service;
			if( $this->_service === 'facebook' ) {
				$this->_facebookOauthService = new Facebook_Client( array(
					'appId'  => FACEBOOK_APP_ID,
					'secret' => FACEBOOK_APP_SECRET
				));
				$this->_facebookUserProfile = $this->_facebookOauthService->getUserProfile();
				if( !empty( $this->_facebookUserProfile ) ) {
					$this->_facebookUserFriends = $this->_facebookOauthService->getUserFriends();
					$this->_authenticated = true;
					$this->_getCurrentUser();
				}
			} else if( $this->_service === 'linkedin' ) {
				$this->_linkedinOauthService = new LinkedIn_LinkedIn( LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET );

				if( isset( $_GET[ 'oauth_token' ] ) && isset( $_GET[ 'oauth_verifier' ] ) ){
					$_SESSION[ 'oauth_verifier' ] = $_GET[ 'oauth_verifier' ];

					$this->_linkedinOauthService->request_token = unserialize( $_SESSION[ 'requestToken' ] );
					$this->_linkedinOauthService->oauth_verifier = $_SESSION[ 'oauth_verifier' ];
					$this->_linkedinOauthService->getAccessToken( $_GET[ 'oauth_verifier' ] );

					$_SESSION[ 'oauth_access_token' ] = serialize( $this->_linkedinOauthService->access_token );
					$profileStr = "~:(id,first-name,last-name,headline,summary,picture-urls::(original),email-address,industry,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes))";
					$xml_response = $this->_linkedinOauthService->getProfile( $profileStr );
					$this->_linkedinUserProfile = @json_decode( @json_encode(simplexml_load_string( $xml_response ) ), 1 );
					$search_response = $this->_linkedinOauthService->searchConnections();
					$this->_linkedinUserFriends = @json_decode( @json_encode(simplexml_load_string( $search_response ) ), 1 );

					$this->_authenticated = true;
					$this->_getCurrentUser();
				}
			} else if( $this->_service === 'twitter' ) {
				$this->_twitterOauthService = new Twitter_Client( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, @$_SESSION[ 'oauth_token' ], @$_SESSION['oauth_token_secret' ] );
				if( !empty( $_GET[ 'oauth_token' ] ) && !empty( $_GET[ 'oauth_verifier' ] ) && !empty( $_SESSION[ 'oauth_token' ] ) && !empty( $_SESSION[ 'oauth_token_secret' ] ) ) {
					$_SESSION[ 'access_token' ] = $this->_twitterOauthService->getAccessToken( $_GET[ 'oauth_verifier' ] );
					$this->_twitterUserProfile = $this->_twitterOauthService->get( 'account/verify_credentials' );
					if( !empty( $this->_twitterUserProfile ) && isset( $this->_twitterUserProfile[ 'id' ] ) ) {
						$this->_authenticated = true;
					}
				}
				if( $this->_authenticated ) {
					$this->_getCurrentUser();
				}
			}
		}

		private function _getCurrentUser() {
			if( $this->_service == 'facebook' ) { // check the social request for facebook
				// check if session is there for requested page or not
				$pageType = isset( $_SESSION[ 'pageType' ] ) ? $_SESSION[ 'pageType' ] : '';
				// check login user exist or not and request is from user verification page then save user data
				if( $this->_eiLoginUserId > 0 && ( $pageType == 'user-verification' || $pageType == 'user-bio' ) && $this->_facebookUserProfile ){
					try{
						// add user's facebook social data
						SocialUtility::saveUserFacebookData( array(
							'userId' => $this->_eiLoginUserId,
							'socialData' => $this->_facebookUserProfile,
							'friends' => $this->_facebookUserFriends
						) );
					}catch( Exception $ex ){
						$this->_message = $ex->getMessage(); 
					}
				}
			}else if( $this->_service == 'linkedin' ) { // check the social request for linkedin
				// check if session is there for requested page or not
				$pageType = isset( $_SESSION[ 'pageType' ] ) ? $_SESSION[ 'pageType' ] : '';
				// check login user exist or not and request is from user verification page then save user data
				if( $this->_eiLoginUserId > 0 && ( $pageType == 'user-verification' || $pageType == 'user-bio' ) && $this->_linkedinUserProfile ){
					try{
						// add user's linkedin social data
						SocialUtility::saveUserLinkedinData( array(
							'userId' => $this->_eiLoginUserId,
							'socialData' => $this->_linkedinUserProfile,
							'friends' => $this->_linkedinUserFriends
						) );
					}catch( Exception $ex ){
						$this->_message = $ex->getMessage(); 
					}
				}
			}
		}

		function getAuthUrl() {
			if( $this->_service == 'facebook' ) {
				return $this->_facebookOauthService->getLoginUrl();			
			} else if( $this->_service == 'linkedin' ) {				
				$this->_linkedinOauthService->getRequestToken();
				$_SESSION['requestToken'] = serialize( $this->_linkedinOauthService->request_token );
				return $this->_linkedinOauthService->generateAuthorizeUrl();
			}
			return 'javascript:;';
		}

		public function _getFbFriends() {
			return $this->_facebookUserFriends;
		}

		public function _getLinkedinFriends() {
			return $this->_linkedinUserFriends;
		}

		function getCurrentUser() {
			return $this->_currentUser;
		}

		function getAuthenticated() {
			return $this->_authenticated;
		}

		function getMessage() {
			return $this->_message;
		}

	}